<?php require VIEWPATH. ADMIN_DIR. DIRECTORY_SEPARATOR. 'header.php'?>
<style type="text/css">
	a:hover{text-decoration: none;}
	.ace-icon.fa-clock-o{margin-right: 3px}
    .holiday-input{
        color: #478FCA;
        background-color: #dff0d8;
        border:none;
        width:90px;
        height:23px;
    }
    .holiday-input:focus{
       outline: none;
    }
    .week-list{text-align: center;margin: 20px 0;}
    .week-list button{margin-right: 5px;}
	.power-time-outer {
		display: flex;
		margin-left: 1.2%;
		margin-bottom: 20px;
		border-left: 1px solid #EDEDED;
	}
	.power-time-outer .item {
		width: 12.5%;
		background: #F8FAFE;
		border-right: 1px solid #EDEDED;
		border-top: 1px solid #EDEDED;
		border-bottom: 1px solid #EDEDED;
	}
	.power-time-outer .item:hover {
		color: #337ab7;
	}
	.power-time-outer .item:active {
		color: #337ab7;
	}
	.power-time-outer .item .top {
		font-weight: bold;
		text-align: center;
		padding: 1rem 0;
		position: relative;
	}
	.power-time-outer .item .top .fa-edit {
		position: absolute;
		right: 5%;
	}
	.power-time-outer .item .bottom {
		display: flex;
		justify-content: center;
		align-items: center;
		flex-wrap: wrap;
		padding-bottom: 5px;
	}
	.power-time-outer .item .bottom span {
		margin-bottom: 8px;
		/* width: 8.4rem; */
		/* width: 43%; */
		text-align: center;
	}
	.a-blue {
		color: #337ab7;
	}
</style>
<div class="page-header">
	<h1>
		定时开关机
		<!-- 教师权限不可批量修改 -->
		<?php if($rmxUser['user_type'] != USER_TYPE_TEACHER): ?>
			<a href="<?= admin_url('brand/grade_power_time') ?>" class="btn btn-info a-custom">
				<i class="ace-icon fa fa-cog"></i> 年级自定义时间
			</a>
			<a href="javascript:;" class="btn btn-info a-custom update-batch">
				<i class="ace-icon fa fa-edit"></i> 批量自定义时间
			</a>
		<?php endif ?>
	</h1>
</div>

<div class="col-xs-12">
	<!-- 教师权限不可批量修改 -->
	<?php if($rmxUser['user_type'] != USER_TYPE_TEACHER): ?>
		<div class="mt10 mb10">
			<i class="ace-icon fa fa-clock-o blue"></i> 放假关机时间段：
			<a class="holiday" href="#modal-holiday" data-toggle="modal" data-id="0">
				<?php if($holidayArr): ?>
					<?php foreach($holidayArr as $holiday): ?>
						<span class="label label-warning mr10"><?= $holiday['startdate'] ?> ~ <?= $holiday['enddate'] ?></span>
					<?php endforeach; ?>
				<?php else: ?>暂未设置<?php endif; ?>
				<i class="fa fa-edit"></i>
			</a>
		</div>
		<div class="mt10 mb10">
			<i class="ace-icon fa fa-clock-o blue"></i> 开机设置：
		</div>
		<div class="power-time-outer">
			<?php foreach($powerTimeArr as $k => $v): ?>
				<a class="item" href="#modal-power-time" data-toggle="modal" data-key="<?= $k ?>">
					<div class="top">
						<span class="week-name"><?= transform_week_to_chinese_long($k) ?></span>
						<i class="fa fa-edit a-blue"></i>
					</div>
					<div class="bottom">
						<?php if($v): ?>
							<?php foreach($v as $k2 => $v2): ?>
								<span class="label label-success <?php if($k2 % 2 == 0): ?>mr10<?php endif ?>">
									<?= $v2['starttime'] ?> - <?= $v2['endtime'] ?>
								</span>
							<?php endforeach ?>	
						<?php else: ?>
							<span class="a-blue">暂未设置</span>
						<?php endif ?>	
					</div>
				</a>
            <?php endforeach ?>
		</div>
	<?php endif ?>	

	<div class="content-filter">
		<!-- 筛选 -->
		<div class="widget-box">
			<div class="widget-header">
				<h4 class="widget-title">内容筛选</h4>
				<div class="widget-toolbar">
					<a href="#" data-action="collapse">
						<i class="ace-icon fa fa-chevron-up"></i>
					</a>
					<a href="#" data-action="close">
						<i class="ace-icon fa fa-times"></i>
					</a>
				</div>
			</div>
			<div class="widget-body">
				<div class="widget-main">
					<div class="form-inline" id="data-search">
						<div class="form-inline keyword-search-div" id="div-grade">
							<label class="keyword-search-label">年级&nbsp;&nbsp;&nbsp;&nbsp;</label>
							<div class="keyword-search-box">
								<a href="javascript:;" class="keyword-search-keyword keyword-search-grade active" data-id="0">全部</a>
								<?php if(isset($gradeList)): ?>
									<?php foreach($gradeList as $grade): ?>
										<a href="javascript:;" class="keyword-search-keyword keyword-search-grade"  data-id="<?=$grade['id']?>"><?=$grade['grade_name']?></a>
									<?php endforeach; ?>
								<?php endif ?>
							</div>
						</div>
					</div>
				</div>
			</div>
		</div>
	</div>

	<table id="dynamic-table" class="table table-striped table-bordered table-hover" style="margin-top:10px">
		<thead>
			<tr>
				<th class="center">
					<label class="check-th">
						<input type="checkbox" class="ace" id="check-first">
						<span class="lbl"></span>
					</label>
				</th>
				<th>班牌ID</th>
				<th>所属校区</th>
				<th>所属班级</th>
				<th>在线状态</th>
				<th>开机时间</th>
				<th>最后上线时间</th>
				<th>最后下线时间</th>
			</tr>
		</thead>
		<tbody>
		</tbody>
	</table>
</div>
<!-- 定时开关机弹窗 -->
<div id="modal-power-time" class="modal fade">
	<input type="hidden" name="week" />
	<div class="modal-dialog">
		<div class="modal-content">
			<div class="modal-header no-padding">
				<div class="table-header">
					<button type="button" class="close" data-dismiss="modal" aria-hidden="true">
						<span class="white">&times;</span>
					</button>
					<!-- 星期几 -->
					<span class="week-name"></span>
				</div>
			</div>
			<div class="modal-body no-padding">
				<div class="row">
					<div class="col-xs-12">
						<form class="form-horizontal mt10">
							<input type="hidden" name="id" />
							<div class="form-group mb10">
								<a href="javascript:;" class="col-sm-4 control-label bolder blue create-power-time"><i class="fa fa-plus"></i> 添加定时开关机时间</a>
							</div>
							<div id="power-time-div"></div>
						</form>
					</div>
				</div>
			</div>
			<div class="modal-footer no-margin-top" >
				<a href="javascript:;" class="btn btn-sm btn-primary" id="save-power-time">
					<i class="ace-icon fa fa-check"></i> 保存
				</a>
			</div>
		</div>
	</div>
</div>
<!-- 放假弹窗 -->
<div id="modal-holiday" class="modal fade">
	<div class="modal-dialog">
		<div class="modal-content">
			<div class="modal-header no-padding">
				<div class="table-header">
					<button type="button" class="close" data-dismiss="modal" aria-hidden="true">
						<span class="white">&times;</span>
					</button>
					<span>放假时间</span>
				</div>
			</div>
			<div class="modal-body no-padding">
				<div class="row">
					<div class="col-xs-12">
						<form class="form-horizontal mt10">
							<div class="form-group mb10">
								<a href="javascript:;" class="col-sm-3 control-label bolder blue create-holiday" style="margin-left:10px;"><i class="fa fa-plus"></i> 添加放假时间</a>
							</div>
							<div id="holiday-div"></div>
						</form>
					</div>
				</div>
			</div>
			<div class="modal-footer no-margin-top" >
				<a href="javascript:;" class="btn btn-sm btn-primary" id="save-holiday">
					<i class="ace-icon fa fa-check"></i> 保存
				</a>
			</div>
		</div>
	</div>
</div>
<?php require VIEWPATH. ADMIN_DIR. DIRECTORY_SEPARATOR. 'footer.php'?>
<script type="text/javascript">
	$(function(){
        // 班牌表格
		var table = $('#dynamic-table').dt({
			"ajaxUrl": '<?=admin_url('brand/get_brand_list')?>',
			"columns": [
				{"data": function(ret){
					return "<div class='center'><label class='check-td'><input type='checkbox' class='ace check-list' value=" + ret.id + "><span class='lbl'></span></label></div>";
				}},	
	            {"data": "id"},
				{"data": "campusName"},
				{"data": "className"},
	            {"data": function(ret){
	            	var onlineState = '<span class="green"><i class="fa fa-circle"></i> 在线</span>';
	            	if(ret.is_online == 0) onlineState = '<span class="light-grey"><i class="fa fa-circle"></i> 离线</span>';
	            	return onlineState;
	            }},
	            {"data": function(ret){
					var powerStr = "";
					if(ret.power_time_v2 == '<?=$powertime?>') {
	            		powerStr = '<a class="power-time text-success" href="<?= admin_url('brand/brand_power_time/') ?>'+ ret.id +'">跟随默认时间 <i class="fa fa-edit"></i></a>';
	            	} else {
	            		powerStr = '<a class="power-time text-danger" href="<?= admin_url('brand/brand_power_time/') ?>'+ ret.id +'">自定义时间 <i class="fa fa-edit"></i></a>';
	            	}
	            	return powerStr;
				}},
				{"data": "online_time"},
	            {"data": "offline_time"},
			]
		});
        // 新增开关机时间
        $("body").on("click", ".create-power-time", function(){
			create_power_time_item("8:00", "18:00");
		});
		// 设置定时开关机时间
		$("body").on("click", ".power-time-outer .item", function(){
			var key = $(this).data("key");
			var weekname = $(this).find(".week-name").text();
			$("#modal-power-time").find(".week-name").text(weekname);
			// 记录星期几
			$("#modal-power-time").find("input[name=week]").val(key);
			// alert(weekname);return;
			// 获取设备开关机时间
			var params = {week: key};
			var getUrl = "<?=admin_url('brand/get_power_time_v2_for_day')?>";
			ajax_get(getUrl, params, function(res) {
				// 清空时间点
				$("#power-time-div").empty();

				for(var i in res.data) {
					var row = res.data[i];
					create_power_time_item(row.starttime, row.endtime);
				}
			});
		});
		// 保存开关机时间
		$("#save-power-time").click(function(){
			// 星期几
			var week = $("#modal-power-time").find("input[name=week]").val();
			var powerTime = new Array();
			$("#power-time-div .form-group").each(function(){
				// 检查内容是否被删除
				if($(this).find(".time-start").length) {
					var timeData = {
						"starttime" : $(this).find(".time-start").text(),
						"endtime": $(this).find(".time-end").text()
					}
					powerTime.push(timeData);
				}
			})
			// 提交到后台
			var params = {
				"brand": 0,
				"time": powerTime,
				"week": week
			};
			// alert(week);return;
			var actionUrl = "<?=admin_url('brand/save_power_time_v2')?>";
			ajax_post(actionUrl, params, function(res){
				window.location.reload();
			})
		});
        // 新增放假时间
        $("body").on("click", ".create-holiday", function(){
            // 今天日期
            var today = "<?= date('Y-m-d') ?>";
            // 明天日期
            var tomorrow = "<?= date('Y-m-d', strtotime('+1 day')) ?>";
			create_holiday_item(today, tomorrow);
		});
		// 设置放假时间
		$("body").on("click", ".holiday", function(){
			// 获取设备开关机时间
			var getUrl = "<?=admin_url('brand/get_power_holiday')?>";
			ajax_get(getUrl, {}, function(res) {
				// 清空时间点
				$("#holiday-div").empty();
				for(var i in res.data) {
					var row = res.data[i];
					create_holiday_item(row.startdate, row.enddate);
				}
            });
		});
		// 保存放假时间
		$("#save-holiday").click(function(){
			var holiday = new Array();
			$("#holiday-div .form-group").each(function(){
                // 检查内容是否被删除
                dateStart = $(this).find("[name=date-start]").val();
                dateEnd = $(this).find("[name=date-end]").val();
				if(dateStart !== undefined && dateStart.length) {
					var dateData = {
						"startdate" : dateStart,
						"enddate": dateEnd
					}
					holiday.push(dateData);
				}
			})
			// 提交到后台
			var params = {
				"holiday": holiday
			};
			var actionUrl = "<?=admin_url('brand/save_power_holiday')?>";
			ajax_post(actionUrl, params, function(res){
				window.location.reload();
			})
        });
 		// 点击每周时间
        $("body").on("click", ".week-list button", function() {
            if($(this).hasClass("btn-success")) {
                $(this).removeClass("btn-success").addClass("btn-danger");
            } else {
                $(this).removeClass("btn-danger").addClass("btn-success");
            }
        });
		// 设置每周时间
		$("body").on("click", ".week", function(){
			// 获取设备开关机时间
			var getUrl = "<?=admin_url('brand/get_power_week')?>";
			ajax_get(getUrl, {}, function(res) {
				for(var i in res.data) {
					var row = res.data[i];
                    $("[data-value=" + row + "]").removeClass("btn-danger").addClass("btn-success");
				}
			});
		});
		// 保存每周时间
		$("#save-power-week").click(function(){
            // 获取选中的星期
            var weekArr = [];
            $(".week-list .btn-success").each(function() {
                weekArr.push($(this).data("value"));
            });
			// 提交到后台
			var params = {
				"weekArr": weekArr
			};
			var actionUrl = "<?=admin_url('brand/save_power_week')?>";
			ajax_post(actionUrl, params, function(res){
				window.location.reload();
			})
		});
		// 全选复选款
		$("#check-first").change(function(e) { 
			var checked =  $("#check-first").is(':checked'); 
			if(checked){
				$('.check-list').each(function (i){
					$(this).prop('checked', true);
				})
			} else{
				$('.check-list').each(function (i){
					$(this).prop('checked', false);
				})
			}
		});
		setTimeout(() => {
			$(".check-list").change(function(e) { 
				var checked = $(this).is(':checked');
				if(checked) {
					var allChecked = true;
					$('.check-list').each(function (i){
						if(!$(this).is(':checked')) {
							allChecked = false;
						}
					})
					if(allChecked) {
						$("#check-first").prop('checked', true);
					} else {
						$("#check-first").prop('checked', false);
					}
				} else {
					$("#check-first").prop('checked', false);
				}
			});
		}, 500);
		setTimeout(() => {
			$(".check-list").change(function(e) { 
				var checked = $(this).is(':checked');
				if(checked) {
					var allChecked = true;
					$('.check-list').each(function (i){
						if(!$(this).is(':checked')) {
							allChecked = false;
						}
					})
					if(allChecked) {
						$("#check-first").prop('checked', true);
					} else {
						$("#check-first").prop('checked', false);
					}
				} else {
					$("#check-first").prop('checked', false);
				}
			});
		}, 2000);
		// 批量自定义时间
		$(".update-batch").click(function(){
			var list = $("input:checkbox.check-list:checked");
			var idArr = new Array();
			list.each(function(){
				idArr.push($(this).val());
			});
			if(idArr.length == 0) {
				tips_alert('请先勾选班牌ID');
				return;
			}
			var idStr = idArr.join(',');
			// base64加密
			var idStr = window.btoa(idStr);
			// console.log(idArr);return;
			window.location.href = "<?= admin_url('brand/power_time_batch_v2?idstr=') ?>" + idStr;
			return;
			var postUrl = "<?= admin_url('brand/power_time_batch_v2') ?>";
			var postData = {"id_arr": idArr};
			ajax_post(postUrl, postData, function(res){
				window.location.reload();
			})
		});

		// 点击关键字
		$("body").on("click", ".keyword-search-keyword", function(){
			// 高亮当前点击对象
			$(this).parent().find(".keyword-search-keyword").removeClass("active");
			$(this).addClass("active");
			// 如果是点击年级
			if($(this).hasClass("keyword-search-grade")) {
				var gradeId = $("#div-grade .active").data("id");
				// 筛选班级
				table.setAjaxData({
					"gradeId": gradeId
				});
			}
		});
    })
	// 生成定时开关机时间
	function create_power_time_item(starttime, endtime) {
		$("#power-time-div").append('<div class="form-group mg0">\
			<div class="col-sm-1"></div>\
			<div class="alert alert-success col-sm-10">\
				<button type="button" class="close" data-dismiss="alert">\
					<i class="ace-icon fa fa-times"></i>\
				</button>\
				<a href="javascript:;" class="timepicker time-start" data-default-time="'+ starttime +'">'+ starttime +'</a> - <a href="javascript:;" class="timepicker  time-end" data-default-time="'+ endtime +'">'+ endtime +'</a>\
			</div>\
		</div>');

		$('.timepicker').timepicker({
				minuteStep: 1,
				showSeconds: false,
				showMeridian: false,
				disableFocus: true,
				icons: {
					up: 'fa fa-chevron-up',
					down: 'fa fa-chevron-down'
				}
			}).on('changeTime.timepicker', function(e) {
				var target = e.currentTarget;
				$(target).text(e.time.value)
			});
	}
	// 生成放假时间
	function create_holiday_item(startDate, endDate) {
		$("#holiday-div").append('<div class="form-group mg0">\
			<div class="col-sm-1"></div>\
			<div class="alert alert-success col-sm-10">\
				<button type="button" class="close" data-dismiss="alert">\
					<i class="ace-icon fa fa-times"></i>\
				</button>\
                <input class="datepicker holiday-input" name="date-start" value="'+ startDate +'" /> ~ &nbsp; <input class="datepicker holiday-input" name="date-end" value="'+ endDate +'" />\
			</div>\
        </div>');
        var today = "<?= date('Y-m-d') ?>";
        $(".datepicker").datepicker({
			autoclose: true,
			todayHighlight: true,
			startDate: "<?= date('Y-m-d') ?>"
        });
    }
</script>